package com.atguigu.search.thread;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/** 线程的几种创建方式
 * @Author ShiJieLin
 * @Date 2022/4/19 10:46
 * @Version 1.0
 */
@Slf4j
public class ThreadTest {

    /** 创建一个线程池，线程数量为10个，线程池应该只有一到两个
     *  所以该放在外面
     */
    static ExecutorService executorService = Executors.newFixedThreadPool(10);

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        log.info("Main方法开始");
        /** 1.继承Thread类，实现run方法
         */
        Thread01 thread01 = new Thread01();
        thread01.start();
        /** 2.实现Runnable接口
         */
        Thread thread = new Thread(new Runnable01());
        thread.start();
        /** 3.实现Callable接口的方式，可以有返回值
         *    但是会阻塞执行，等到获取到返回值结果之后。
         */
        FutureTask<Integer> futureTask = new FutureTask<Integer>(new Callable01());
        new Thread(futureTask).start();
        Integer integer = futureTask.get();
        System.out.println(integer);

        executorService.execute(new Runnable01());


        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(2, 10, 20, TimeUnit.SECONDS,
                null, null, null);

        poolExecutor.allowCoreThreadTimeOut(true);

        Executors.newScheduledThreadPool(10);
        log.info("Main方法结束");
    }

    static class Thread01 extends Thread{
       @Override
        public void run() {

           log.info("当前线程：{}", Thread.currentThread().getId());

           int i = 10 / 5;

           log.info("运行结果：i = {}", i);
        }
    }
    static class Runnable01 implements Runnable{

        @Override
        public void run() {

            log.info("当前线程：{}", Thread.currentThread().getId());

            int i = 10 / 5;

            log.info("运行结果：i = {}", i);
        }
    }

    static class Callable01 implements Callable<Integer>{

        @Override
        public Integer call() throws Exception {
            log.info("当前线程：{}", Thread.currentThread().getId());

            int i = 10 / 5;

            log.info("运行结果：i = {}", i);

            return i;
        }
    }
}
